"use client";

import React, { useState, useEffect } from "react";
import {
	Form,
	Input,
	Button,
	Space,
	message,
	Typography,
	Select,
	Collapse,
	Modal
} from "antd";
import type { FormInstance } from 'antd/es/form';
import { PlusOutlined } from "@ant-design/icons";
import { 
	getRecruitmentAnnouncements, 
	updateRecruitmentAnnouncement,
	createDeptPositions,
	deleteDeptPositions,
	ApiResponse
} from '@/lib/recruitment';
import { getAllDepartments as getAllDepartmentsFromDepartments } from '@/lib/departments';
import { getAcademyList as getAcademyListFromAcademy } from '@/lib/academy';
import { getAllOtherDepartments as getAllOtherDepartmentsFromOtherDept } from '@/lib/otherdept';

const { Title } = Typography;
const { Panel } = Collapse;

/* 数据接口类型定义 */
export interface PositionData {
	positionNumber: string;
	positionName: string;
	positionProperties: string;
	// 岗位描述由模板回填，用户不可修改
	jobDescription: string;
	jobRequired: string;
	person: number;
	professionalSkillsRight: number;
	communicationSkillsRight: number;
	teamworkAbilityRight: number;
	// 更新接口可选字段
	content?: string;
}

export interface DeptData {
	// 页面上用人部门的编号（提交时转换为 numbering）
	deptSelect: string;
	positions: PositionData[];
}

interface DeptManageProps {
	selectedPlanId: string;
	onCancel: () => void;
	onSuccess: () => void;
}

const DeptManagePage: React.FC<DeptManageProps> = ({ selectedPlanId, onCancel, onSuccess }) => {
	// 招聘公告数据（包含 planId 与 planType）
	const [announcement, setAnnouncement] = useState<any>(null);
	// 招聘计划类型，本示例只处理 planType === 1
	const [planType, setPlanType] = useState<number>(1);
	// 用人部门及其岗位
	const [depts, setDepts] = useState<DeptData[]>([]);
	// 部门下拉选项（用于新增用人部门和岗位）
	const [deptOptions, setDeptOptions] = useState<any[]>([]);

	// ============== 更新岗位相关状态 ==============
	const [updateModalVisible, setUpdateModalVisible] = useState(false);
	const [updateForm] = Form.useForm();
	// 记录当前编辑的部门和岗位索引
	const [updateDeptIndex, setUpdateDeptIndex] = useState<number | null>(null);
	const [updatePosIndex, setUpdatePosIndex] = useState<number | null>(null);

	// ============== 新增岗位（已有部门下）相关状态 ==============
	const [addModalVisible, setAddModalVisible] = useState(false);
	const [addForm] = Form.useForm();
	// 当前在哪个部门下新增岗位
	const [addDeptIndex, setAddDeptIndex] = useState<number | null>(null);

	// ============== 新增用人部门和岗位（当页面无部门时） ==============
	const [deptAddModalVisible, setDeptAddModalVisible] = useState(false);
	const [deptAddForm] = Form.useForm();

	// 添加一个状态来控制岗位选择的重新渲染
	const [selectedDepartment, setSelectedDepartment] = useState<string | null>(null);

	// 模拟岗位模板数据（实际可通过接口获取）
	const jobTemplates: Record<string, any> = {
		D1: {
			positionNumber: "111",
			positionName: "类造完众",
			positionProperties: "aute dolor eiusmod ex",
			jobDescription: "anim do"
		},
		D2: {
			positionNumber: "222",
			positionName: "示例岗位",
			positionProperties: "示例性质",
			jobDescription: "示例描述"
		}
	};

	const fetchData = async () => {
		try {
			const response = await getRecruitmentAnnouncements();
			if (response && response.code === 1) {
				const currentPlan = response.data.find(
					(plan: any) => plan.planId === parseInt(selectedPlanId)
				);
				if (currentPlan) {
					setAnnouncement(currentPlan);
					setPlanType(currentPlan.planType);
					setDepts(currentPlan.depts || []);
				} else {
					message.error("未找到对应的招聘计划");
				}
			} else {
				message.error(response?.message || "获取数据失败");
			}
		} catch (error) {
			console.error("获取数据失败:", error);
			message.error("获取数据失败");
		}
	};

	useEffect(() => {
		if (selectedPlanId) {
			fetchData();
		}
	}, [selectedPlanId]);

	// ---------------- 编辑岗位（更新） ----------------
	const showUpdateModal = (deptIdx: number, posIdx: number) => {
		setUpdateDeptIndex(deptIdx);
		setUpdatePosIndex(posIdx);
		const position = depts[deptIdx].positions[posIdx];
		// 设置表单初始数据，岗位描述字段只读
		updateForm.setFieldsValue({
			numbering: depts[deptIdx].deptSelect,
			positionName: position.positionName,
			jobDescription: position.jobDescription,
			jobRequired: position.jobRequired,
			person: position.person,
			professionalSkillsRight: position.professionalSkillsRight,
			communicationSkillsRight: position.communicationSkillsRight,
			teamworkAbilityRight: position.teamworkAbilityRight,
			content: position.content || ""
		});
		setUpdateModalVisible(true);
	};

	const handleUpdateSubmit = async () => {
		try {
			const values = await updateForm.validateFields();
			if (updateDeptIndex === null || updatePosIndex === null) return;
			const targetDept = depts[updateDeptIndex];
			const targetPosition = targetDept.positions[updatePosIndex];
			
			const response = await updateRecruitmentAnnouncement({
				planId: parseInt(selectedPlanId),
				numbering: targetDept.deptSelect,
				positionName: targetPosition.positionName,
				jobDescription: targetPosition.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
				content: values.content
			});
			
			if (response.data.code === 1) {
				message.success("更新成功");
				setUpdateModalVisible(false);
				fetchData();
			} else {
				message.error(response.data.message || "更新失败");
			}
		} catch (error) {
			message.error("更新失败");
		}
	};

	// ---------------- 新增岗位（已有部门下） ----------------
	const showAddModal = (deptIdx: number) => {
		setAddDeptIndex(deptIdx);
		addForm.resetFields();
		const currentDeptNumber = depts[deptIdx].deptSelect;
		console.log('新增岗位 - 当前部门编号:', currentDeptNumber);
		console.log('新增岗位 - 当前部门索引:', deptIdx);
		console.log('新增岗位 - 当前部门数据:', depts[deptIdx]);

		// 回填当前部门编号
		addForm.setFieldsValue({ 
			numbering: currentDeptNumber,
			deptName: getDepartmentName(currentDeptNumber)
		});
		setAddModalVisible(true);
	};

	// 修改获取部门名称的函数
	const getDepartmentName = (deptNumber: string) => {
		console.log('正在查找部门名称:');
		console.log('查找的部门编号:', deptNumber);
		console.log('当前计划类型:', planType);
		console.log('可用的部门选项:', deptOptions);

		// 根据计划类型和部门编号查找对应的部门名称
		const department = deptOptions.find(dept => {
			console.log('正在比较部门:', dept);
			console.log('部门编号比较:', dept.number, deptNumber);
			return dept.number === deptNumber;
		});

		console.log('找到的部门:', department);
		
		if (department) {
			const name = `${department.name}（编号：${department.number}）`;
			console.log('返回的部门名称:', name);
			return name;
		}

		console.log('未找到部门，返回未知部门');
		return '未知部门';
	};

	// 修改岗位选择的处理函数
	const handleJobSelect = (value: string, departmentNumber: string, form: FormInstance) => {
		// 找到对应的部门
		const department = deptOptions.find(dept => dept.number === departmentNumber);
		console.log('找到的部门:', department);
		console.log('部门编号:', departmentNumber);
		console.log('选中的岗位编号:', value);

		if (department) {
			// 找到选中的岗位
			const selectedPosition = department.positions?.find(
				(pos: any) => pos.positionNumber === value
			);
			console.log('找到的岗位:', selectedPosition);

			if (selectedPosition) {
				// 设置表单值
				form.setFieldsValue({
					positionNumber: selectedPosition.positionNumber,
					positionName: selectedPosition.positionName,
					positionProperties: selectedPosition.positionProperties || '',
					jobDescription: selectedPosition.jobDescription
				});
			}
		}
	};

	const handleAddSubmit = async () => {
		try {
			const values = await addForm.validateFields();
			if (addDeptIndex === null) return;
			const targetDept = depts[addDeptIndex];
			
			const response = await updateRecruitmentAnnouncement({
				planId: parseInt(selectedPlanId),
				numbering: targetDept.deptSelect,
				positionName: values.positionName,
				jobDescription: values.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
				content: values.content
			});
			
			if (response.data.code === 1) {
				message.success("添加成功");
				setAddModalVisible(false);
				fetchData();
			} else {
				message.error(response.data.message || "添加失败");
			}
		} catch (error) {
			message.error("添加失败");
		}
	};

	// ---------------- 新增用人部门和岗位（页面无部门时） ----------------
	const showDeptAddModal = () => {
		deptAddForm.resetFields();
		setDeptAddModalVisible(true);
	};

	const handleDeptAddSubmit = async () => {
		try {
			const values = await deptAddForm.validateFields();
			const response = await updateRecruitmentAnnouncement({
				planId: parseInt(selectedPlanId),
				numbering: values.deptSelect,
				positionName: values.positionName,
				jobDescription: values.jobDescription,
				jobRequired: values.jobRequired,
				person: values.person,
				professionalSkillsRight: values.professionalSkillsRight,
				communicationSkillsRight: values.communicationSkillsRight,
				teamworkAbilityRight: values.teamworkAbilityRight,
				content: values.content
			});
			
			if (response.data.code === 1) {
				message.success("添加成功");
				setDeptAddModalVisible(false);
				fetchData();
			} else {
				message.error(response.data.message || "添加失败");
			}
		} catch (error) {
			message.error("添加失败");
		}
	};

	// ---------------- 删除岗位 ----------------
	const confirmDeletePosition = (deptIdx: number, posIdx: number) => {
		Modal.confirm({
			title: "确认删除该岗位？",
			onOk: async () => {
				try {
					const deptNumber = depts[deptIdx].deptSelect;
					const positionName = depts[deptIdx].positions[posIdx].positionName;
					
					// 确保 planId 存在
					if (!announcement?.planId) {
						message.error('招聘计划ID不能为空');
						return;
					}

					const payload = {
						delPositions: [
							{
								planId: announcement.planId,
								numbering: deptNumber,
								positionName: positionName
							}
						]
					};

					console.log('删除岗位请求参数:', payload);
					const response = await deleteDeptPositions(payload);
					console.log('删除岗位响应:', response);

					if (response && response.code === 1) {
						message.success("删除成功");
						fetchData();
					} else {
						message.error(response?.message || "删除失败");
					}
				} catch (error) {
					console.error("删除岗位失败:", error);
					message.error("删除失败");
				}
			}
		});
	};

	// 修改部门选择的渲染
	const renderDeptSelect = () => {
		const planTypeText = {
			1: '职能部门',
			2: '学院',
			3: '其他部门'
		}[planType];

		return (
			<Form.Item 
				label={`选择${planTypeText}`}
				name="deptSelect" 
				rules={[{ required: true, message: `请选择${planTypeText}` }]}
			>
				<Select onChange={(value) => {
					console.log('选择部门时的值:', value);
					console.log('当前所有部门选项:', deptOptions);
					const selectedDept = deptOptions.find(dept => dept.number === value);
					console.log('选中的部门:', selectedDept);
					console.log('该部门下的岗位:', selectedDept?.positions);

					// 清空岗位相关的字段
					deptAddForm.setFieldsValue({
						jobSelect: undefined,
						positionNumber: '',
						positionName: '',
						positionProperties: '',
						jobDescription: ''
					});

					// 强制触发表单重新渲染
					deptAddForm.validateFields(['jobSelect']);
				}}>
					{deptOptions.map(dept => {
						console.log('渲染部门选项:', dept);
						return (
							<Select.Option key={dept.number} value={dept.number}>
								{dept.name}（编号：{dept.number}）
							</Select.Option>
						);
					})}
				</Select>
			</Form.Item>
		);
	};

	// 修改渲染岗位选择的部分
	const renderPositionSelect = (departmentNumber: string, form: FormInstance) => {
		const department = deptOptions.find(dept => dept.number === departmentNumber);
		console.log('渲染岗位选择 - 部门编号:', departmentNumber);
		console.log('渲染岗位选择 - 找到的部门:', department);

		if (!department) return null;

		return (
			<Form.Item 
				label="选择岗位" 
				name="jobSelect" 
				rules={[{ required: true, message: "请选择岗位" }]}
			>
				<Select onChange={(value) => handleJobSelect(value, departmentNumber, form)}>
					{department.positions.map((pos: any) => {
						console.log('渲染岗位选项:', pos);
						return (
							<Select.Option key={pos.positionNumber} value={pos.positionNumber}>
								{pos.positionName}（编号：{pos.positionNumber}）
							</Select.Option>
						);
					})}
				</Select>
			</Form.Item>
		);
	};

	return (
		<div style={{ padding: "20px" }}>
			<Title level={3}>招聘计划岗位管理 - {selectedPlanId}</Title>
			{/* 如果有用人部门，则显示列表；否则显示添加用人部门和岗位的按钮 */}
			{depts && depts.length > 0 ? (
				<Collapse>
					{depts.map((dept, deptIdx) => (
						<Panel 
							header={`用人部门：${getDepartmentName(dept.deptSelect)}`}
							key={dept.deptSelect}
						>
							{dept.positions.map((pos, posIdx) => (
								<div
									key={pos.positionNumber + pos.positionName}
									style={{
										marginBottom: "10px",
										border: "1px solid #ccc",
										padding: "10px"
									}}
								>
									<div>岗位编号：{pos.positionNumber}</div>
									<div>岗位名称：{pos.positionName}</div>
									<div>岗位性质：{pos.positionProperties}</div>
									<div>岗位描述：{pos.jobDescription}</div>
									<div>任职要求：{pos.jobRequired}</div>
									<div>招聘人数：{pos.person}</div>
									<div>专业技能的权：{pos.professionalSkillsRight}</div>
									<div>沟通能力的权：{pos.communicationSkillsRight}</div>
									<div>团队协作的权：{pos.teamworkAbilityRight}</div>
									<Space style={{ marginTop: "10px" }}>
										<Button
											type="primary"
											onClick={() => showUpdateModal(deptIdx, posIdx)}
										>
											编辑
										</Button>
										<Button danger onClick={() => confirmDeletePosition(deptIdx, posIdx)}>
											删除
										</Button>
									</Space>
								</div>
							))}
							<Button
								type="dashed"
								icon={<PlusOutlined />}
								onClick={() => showAddModal(deptIdx)}
							>
								新增岗位
							</Button>
						</Panel>
					))}
				</Collapse>
			) : (
				<div>
					{(planType === 1 || planType === 2) && (
						<Button type="dashed" icon={<PlusOutlined />} onClick={showDeptAddModal}>
							添加用人部门和岗位
						</Button>
					)}
				</div>
			)}

			{/* 更新岗位模态框 */}
			<Modal
				title="更新岗位"
				visible={updateModalVisible}
				onCancel={() => setUpdateModalVisible(false)}
				onOk={handleUpdateSubmit}
			>
				<Form form={updateForm} layout="vertical">
					<Form.Item label="用人部门编号" name="numbering">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位名称" name="positionName">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位描述" name="jobDescription">
						<Input.TextArea readOnly />
					</Form.Item>
					<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
						<Input.TextArea />
					</Form.Item>
					<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="专业技能的权"
						name="professionalSkillsRight"
						rules={[{ required: true, message: "请输入专业技能的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="沟通能力的权"
						name="communicationSkillsRight"
						rules={[{ required: true, message: "请输入沟通能力的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="团队协作的权"
						name="teamworkAbilityRight"
						rules={[{ required: true, message: "请输入团队协作的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item label="内容" name="content">
						<Input />
					</Form.Item>
				</Form>
			</Modal>

			{/* 新增岗位模态框（已有部门下） */}
			<Modal
				title="新增岗位"
				visible={addModalVisible}
				onCancel={() => setAddModalVisible(false)}
				onOk={handleAddSubmit}
			>
				<Form form={addForm} layout="vertical">
					<Form.Item label="用人部门" name="numbering">
						<Input readOnly value={addDeptIndex !== null ? getDepartmentName(depts[addDeptIndex].deptSelect) : ''} />
					</Form.Item>
					{/* 添加岗位选择 */}
					{addDeptIndex !== null && (
						<Form.Item 
							label="选择岗位" 
							name="jobSelect" 
							rules={[{ required: true, message: "请选择岗位" }]}
						>
							<Select onChange={(value) => handleJobSelect(value, depts[addDeptIndex].deptSelect, addForm)}>
								{deptOptions.find(dept => dept.number === depts[addDeptIndex].deptSelect)?.positions.map((pos: any) => (
									<Select.Option key={pos.positionNumber} value={pos.positionNumber}>
										{pos.positionName}（编号：{pos.positionNumber}）
									</Select.Option>
								))}
							</Select>
						</Form.Item>
					)}
					<Form.Item label="岗位编号" name="positionNumber">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位名称" name="positionName">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位性质" name="positionProperties">
						<Input readOnly />
					</Form.Item>
					<Form.Item label="岗位描述" name="jobDescription">
						<Input.TextArea readOnly />
					</Form.Item>
					<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
						<Input.TextArea />
					</Form.Item>
					<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="专业技能的权"
						name="professionalSkillsRight"
						rules={[{ required: true, message: "请输入专业技能的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="沟通能力的权"
						name="communicationSkillsRight"
						rules={[{ required: true, message: "请输入沟通能力的权" }]}
					>
						<Input type="number" />
					</Form.Item>
					<Form.Item
						label="团队协作的权"
						name="teamworkAbilityRight"
						rules={[{ required: true, message: "请输入团队协作的权" }]}
					>
						<Input type="number" />
					</Form.Item>
				</Form>
			</Modal>

			{/* 新增用人部门和岗位模态框（当页面无部门时使用） */}
			{(planType === 1 || planType === 2) && (
				<Modal
					title="新增用人部门和岗位"
					visible={deptAddModalVisible}
					onCancel={() => setDeptAddModalVisible(false)}
					onOk={handleDeptAddSubmit}
				>
					<Form form={deptAddForm} layout="vertical">
						{/* 部门选择 */}
						<Form.Item 
							label={`选择${planType === 1 ? '职能部门' : '学院'}`}
							name="deptSelect" 
							rules={[{ required: true, message: `请选择${planType === 1 ? '职能部门' : '学院'}` }]}
						>
							<Select 
								placeholder={`请选择${planType === 1 ? '职能部门' : '学院'}`}
								onChange={(value) => {
									console.log('部门选择变化:', value);
									
									// 清空岗位相关的字段
									deptAddForm.setFieldsValue({
										jobSelect: undefined,
										positionNumber: '',
										positionName: '',
										positionProperties: '',
										jobDescription: ''
									});

									// 更新选中的部门
									setSelectedDepartment(value);

									// 获取新选择的部门的岗位
									const selectedDept = deptOptions.find(dept => dept.number === value);
									console.log('新选择的部门:', selectedDept);
									console.log('该部门下的岗位:', selectedDept?.positions);
								}}
							>
								{deptOptions.map(dept => (
									<Select.Option key={dept.number} value={dept.number}>
										{dept.name}（编号：{dept.number}）
									</Select.Option>
								))}
							</Select>
						</Form.Item>
						
						{/* 岗位选择 */}
						<Form.Item 
							label="选择岗位" 
							name="jobSelect" 
							rules={[{ required: true, message: "请选择岗位" }]}
						>
							<Select 
								key={selectedDepartment} // 添加key强制重新渲染
								placeholder="请先选择部门"
								onChange={(value) => {
									console.log('岗位选择变化:', value);
									const selectedDeptNumber = deptAddForm.getFieldValue('deptSelect');
									handleJobSelect(value, selectedDeptNumber, deptAddForm);
								}}
							>
								{(() => {
									const selectedDeptNumber = deptAddForm.getFieldValue('deptSelect');
									if (!selectedDeptNumber) return [];

									const selectedDept = deptOptions.find(dept => dept.number === selectedDeptNumber);
									console.log('当前选中的部门:', selectedDept);
									
									if (!selectedDept?.positions) return [];
									
									return selectedDept.positions.map((pos: any) => {
										console.log('渲染岗位选项:', pos);
										return (
											<Select.Option key={pos.positionNumber} value={pos.positionNumber}>
												{pos.positionName}（编号：{pos.positionNumber}）
											</Select.Option>
										);
									});
								})()}
							</Select>
						</Form.Item>
						
						{/* 岗位信息表单项 */}
						<Form.Item label="岗位编号" name="positionNumber">
							<Input readOnly />
						</Form.Item>
						<Form.Item label="岗位名称" name="positionName">
							<Input readOnly />
						</Form.Item>
						<Form.Item label="岗位性质" name="positionProperties">
							<Input readOnly />
						</Form.Item>
						<Form.Item label="岗位描述" name="jobDescription">
							<Input.TextArea readOnly />
						</Form.Item>
						<Form.Item label="任职要求" name="jobRequired" rules={[{ required: true, message: "请输入任职要求" }]}>
							<Input.TextArea />
						</Form.Item>
						<Form.Item label="招聘人数" name="person" rules={[{ required: true, message: "请输入招聘人数" }]}>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="专业技能的权"
							name="professionalSkillsRight"
							rules={[{ required: true, message: "请输入专业技能的权" }]}
						>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="沟通能力的权"
							name="communicationSkillsRight"
							rules={[{ required: true, message: "请输入沟通能力的权" }]}
						>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="团队协作的权"
							name="teamworkAbilityRight"
							rules={[{ required: true, message: "请输入团队协作的权" }]}
						>
							<Input type="number" />
						</Form.Item>
					</Form>
				</Modal>
			)}
		</div>
	);
};

// 修改页面组件
const Page = ({ params }: { params: { id: string } }) => {
	return (
		<DeptManagePage
			selectedPlanId={params.id}
			onCancel={() => {}}
			onSuccess={() => {}}
		/>
	);
};

export default Page;